package com.yunxiangyue

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.yunxiangyue.app.R
import com.yunxiangyue.room_login_info.LogDao
import com.yunxiangyue.room_login_info.LogDataBase
import com.yunxiangyue.room_login_info.LogInfo

const val testMode = false

//首次注册登录进去后将跳转至信息修改页面  保存信息后该用户信息才会添加至数据库中
//如何判断首次：用对应的号码去查找数据库是否有该用户   从服务端返回firstLogin则跳转至信息页面  否则不需要；
class Login : ComponentActivity(), View.OnClickListener, View.OnFocusChangeListener,
    ViewPager.OnPageChangeListener {


    private lateinit var infoList: List<LogInfo>
    private lateinit var InfoDao: LogDao
    private lateinit var phone:EditText
    private lateinit var pwd:EditText
    private lateinit var check1:CheckBox
    private lateinit var check2:CheckBox
    private lateinit var viewPager:ViewPager
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        val viewpager:ViewPager = findViewById(R.id.viewPager)
        var views:MutableList<View> = ArrayList<View>()
        var title:MutableList<String> = ArrayList<String>()
        viewpager.addOnPageChangeListener(this)
        val viewRegister = LayoutInflater.from(this).inflate(R.layout.register_page,null)
        val viewForget = LayoutInflater.from(this).inflate(R.layout.forgetpwd_page,null)
        views.add(viewRegister)
        views.add(viewForget)
        title.add("登录账号")
        title.add("验证码登录")
        val adpter:RegisterAddForgetAdapter = RegisterAddForgetAdapter(views,title)
        val tabLay = findViewById<TabLayout>(R.id.tab)
        for (t in title){
            tabLay.addTab(tabLay.newTab().setText(t))
        }
        pwd = viewRegister.findViewById(R.id.pwd_edit)
        phone = viewRegister.findViewById(R.id.phone_e)
        val viewPager:ViewPager = findViewById(R.id.viewPager)
        val textRegistr2 = viewRegister.findViewById<TextView>(R.id.register2)
        val textReister:TextView = viewForget.findViewById(R.id.register)
        check1 = viewRegister.findViewById(R.id.checkBox)
        check2 = viewForget.findViewById(R.id.check2)
        val notarize_btn = viewRegister.findViewById<Button>(R.id.nota_btn1)
        val notarize_btn2 = viewForget.findViewById<Button>(R.id.nota_btn2)
        textRegistr2.setOnClickListener(this)
        textReister.setOnClickListener(this)
        tabLay.setupWithViewPager(viewPager)
        viewPager.adapter = adpter
        InfoDao = LogDataBase.getLogDatabase(this).logDao()
        phone.setOnFocusChangeListener(this)
        pwd.setOnFocusChangeListener(this)
        notarize_btn.setOnClickListener(this)
        notarize_btn2.setOnClickListener(this)
    }

    //重新恢复登录页时  密码置空
    override fun onResume() {
        super.onResume()
        pwd.setText("")
        pwd.requestFocus()
    }


    private fun logInfo():Boolean{
        infoList = InfoDao.queryAllInfo()
        if(TextUtils.isEmpty(phone.text.toString())){
            Toast.makeText(this,"手机号码不能为空",Toast.LENGTH_LONG).show()
            phone.setText("")
            return false
        }
        if(TextUtils.isEmpty(pwd.text.toString())){
            Toast.makeText(this,"登录密码不能为空",Toast.LENGTH_LONG).show()
            pwd.setText("")
            return false
        }
        if(pwd.text.toString().length<6||pwd.text.toString().length>18){
            Toast.makeText(this,"密码只能在6—18位",Toast.LENGTH_LONG).show()
            pwd.setText("")
            return false
        }
        if(phone.text.toString().length!=11){
            Toast.makeText(this,"手机号码只能是11位",Toast.LENGTH_LONG).show()
            return false
        }

        if(!judegePhoneFormat(phone.text.toString())){
            Toast.makeText(this,"手机号码格式错误",Toast.LENGTH_LONG).show()
            phone.setText("")
            return false
        }
        return true
    }

    private fun judegePhoneFormat(phone:String):Boolean{
        val phoneFormat = "^1[3-9]\\d{9}\$".toRegex()
        if(TextUtils.isEmpty(phone)){
            return false
        }else{
            return phone.matches(phoneFormat)
        }

    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.register -> {
                val intent = Intent(this,Register_page::class.java)
                startActivity(intent)
            }

            R.id.register2 -> {
                val intent = Intent(this,Register_page::class.java)
                startActivity(intent)
            }

            R.id.pwd_edit -> {
                phoneJudge()
            }
            //当点击号码与密码登录页的确认按钮
            R.id.nota_btn1 -> {
                if (testMode) {
                    //登陆成功跳转页面
                    Toast.makeText(this,"登陆成功",Toast.LENGTH_SHORT).show()
                    val intent = Intent(this@Login,framlayoutActivity::class.java)
                    intent.putExtra("phone",phone.text.toString())
                    startActivity(intent)
                } else {
                    if(phonePwdJudge()){
                        if(check1.isChecked || check2.isChecked){
                            val li:List<LogInfo> = InfoDao.queryByPhone_List(phone.text.toString())
                            Log.d("ning","查询的用户为${li.get(0).phone}"+"密码为：${li.get(0).pwd}")
                            var flag = false
                            for(loginfo in li){
                                if(loginfo.phone == phone.text.toString()){
                                    Log.d("ning","查询的用户为${loginfo.phone}"+"密码为：${loginfo.pwd}")
                                    flag = true
                                    if(loginfo.pwd == pwd.text.toString()){
                                        //登陆成功跳转页面
                                        Toast.makeText(this,"登陆成功",Toast.LENGTH_SHORT).show()
                                        val intent = Intent(this@Login,framlayoutActivity::class.java)
                                        intent.putExtra("phone",phone.text.toString())
                                        startActivity(intent)
                                    }else{
                                        Toast.makeText(this,"密码错误，请重新输入",Toast.LENGTH_SHORT).show()
                                        pwd.requestFocus()
                                        pwd.setText("")
                                    }
                                }
                            }
                            if(!flag){
                                Toast.makeText(this,"该账号不存在，请注册后登陆",Toast.LENGTH_SHORT).show()
                                pwd.setText("")
                                phone.requestFocus()
                                phone.setText("")
                            }
                        }else{
                            Toast.makeText(this,"请先勾选服务",Toast.LENGTH_SHORT).show()
                        }
                }

                }
            }
//当点击验证码登录页的确认按钮
            R.id.nota_btn2 -> {
                //按照手机号码发送验证码  且该手机号码已经注册并且手机号码存在才能正确发送

            }
        }
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

    }

    override fun onPageScrollStateChanged(state: Int) {


    }

    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        when(v?.id){
            R.id.pwd -> {
                phoneJudge()

            }
        }
    }


    private fun phonePwdJudge():Boolean{
        var flag = true
        flag = phoneJudge()
        if (TextUtils.isEmpty(pwd.text.toString())) {
            Toast.makeText(this, "登录密码不能为空", Toast.LENGTH_LONG).show()
            pwd.requestFocus()
            pwd.setText("")
            flag = false
        }else if (pwd.text.toString().length < 6 || pwd.text.toString().length > 18){
            Toast.makeText(this, "密码只能在6—18位", Toast.LENGTH_LONG).show()
            pwd.requestFocus()
            pwd.setText("")
            flag = false
        }
        return flag
    }


    private fun phoneJudge():Boolean{
        var flag = true
        if (TextUtils.isEmpty(phone.text.toString())||phone.text.toString().length != 11) {
            Toast.makeText(this, "手机号码不能为空且只能为11位", Toast.LENGTH_LONG).show()
            phone.requestFocus()
            phone.setText("")
            pwd.setText("")
            flag = false
        }else if(!judegePhoneFormat(phone.text.toString())){
            Toast.makeText(this, "手机号码格式错误", Toast.LENGTH_LONG).show()
            phone.requestFocus()
            phone.setText("")
            pwd.setText("")
            flag = false
        }
        return flag
    }

    override fun onPageSelected(position: Int) {
        if(position == 0){
            if(check1.isChecked){
                check1.isChecked = false
            }
        }else if(position==1){
            if(check2.isChecked){
                check2.isChecked = false
            }
        }
    }
}
